package LC;

/**
 * https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
 * Given a sorted linked list, delete all duplicates such that each element appear only once.
 * For example,
 * Given 1->1->2, return 1->2.
 * Given 1->1->2->3->3, return 1->2->3.
 */
public class LC_083_RemoveDuplicatesfromSortedList_LinkedList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        head.next.next = new ListNode(2);
        ListNode h = Solution.deleteDuplicates(head);
        ListNode cur = h;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static ListNode deleteDuplicates(ListNode head) {
            if (head == null || head.next == null)
                return head;

            ListNode prev = head;
            ListNode p = head.next;

            while (p != null) {
                if (p.val == prev.val) {
                    prev.next = p.next;
                    p = p.next;
                } else {
                    prev = p;
                    p = p.next;
                }
            }

            return head;
        }
    }

    static class Solution_2 {
        static ListNode deleteDuplicates(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode p = head;

            while (p.next != null) {
                if (p.val == p.next.val)
                    p.next = p.next.next;
                else
                    p = p.next;
            }

            return head;
        }
    }
}
